<template>
  <div>
    <el-dialog :visible.sync="addOrderDialog" :title="title"
               width="50%"
               center top="50px">
      <el-form :model="data" ref="taskForm"
               :rules="rules"
               v-loading="loading"
               style="display:flex;justify-content:space-around;flex-wrap: wrap;align-items: flex-start"
               label-width="110px"
      >

        <el-form-item label="店铺名称：" prop="storeId">
          <el-select v-model="data.storeId" size="small" :disabled="true">
            <el-option v-for="item in storeData" :value="item.storeId" :label="item.storeName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监理：" prop="chargeUserId">
          <el-select size="small" clearable v-model="data.chargeUserId"
                     placeholder="请选择监理人">
            <el-option v-for="item in menageList" :key="item.userId" :label="item.userName"
                       :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售后人员：" prop="afterId">
          <el-select size="small" clearable v-model="data.afterId"
                     placeholder="请选择售后人员" @change="getAfterSalesPhone">
            <el-option v-for="item in afterSaleList" :key="item.userId" :label="item.userName"
                       :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售后电话：" prop="afterPhone">
          <el-input size="small" clearable v-model="data.afterPhone"></el-input>
        </el-form-item>
        <el-form-item label="设计人员：" prop="designId">
          <el-select size="small" clearable filterable v-model="data.designId"
                     placeholder="请选择">
            <el-option v-for="item in designList" :key="item.userId" :label="item.userName"
                       :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预结算人员：" prop="settlementId">
          <el-select size="small" clearable filterable v-model="data.settlementId"
                     placeholder="请选择">
            <el-option v-for="item in yjsList" :key="item.userId" :label="item.userName"
                       :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="装修公司：" prop="companyId">
          <el-select size="small" clearable v-model="data.companyId"
                     placeholder="请选择" @change="changeCompanyId" :disabled="title=='修改订单信息'&&data.status>=1">
            <el-option v-for="item in furnishList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="装修模板：" prop="templateId">
          <el-select size="small" clearable v-model="data.templateId"
                     placeholder="请选择模板" :disabled="title=='修改订单信息'">
            <el-option v-for="item in furnishTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="冷链公司：" prop="coldCompanyId">
          <el-select size="small" clearable v-model="data.coldCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in coldList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="冷链模板：" prop="clodTemplateId">
          <el-select size="small" clearable v-model="data.clodTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in coldTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监控公司：" prop="monitorCompanyId">
          <el-select size="small" clearable v-model="data.monitorCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in cctvList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监控模板：" prop="monitorTemplateId">
          <el-select size="small" clearable v-model="data.monitorTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in cctvTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货架公司：" prop="goodsCompanyId" v-if="userData.brandPartyId!=3">
          <el-select size="small" clearable v-model="data.goodsCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in shelvesList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货架模板：" prop="goodsTemplateId" v-if="userData.brandPartyId!=3">
          <el-select size="small" clearable v-model="data.goodsTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in shelvesTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告公司：" prop="adCompanyId">
          <el-select size="small" clearable v-model="data.adCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in addvanceList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告模板：" prop="adTemplateId">
          <el-select size="small" clearable v-model="data.adTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in addvanceTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门窗、收银台公司：" prop="windowsCompanyId">
          <el-select size="small" clearable v-model="data.windowsCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in doorList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门窗、收银台模板：" prop="windowsTemplateId">
          <el-select size="small" clearable v-model="data.windowsTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in doorTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电宝公司：" prop="hotCompanyId" v-if="userData.brandPartyId==3">
          <el-select size="small" clearable v-model="data.powerCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in cdbList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电宝模板：" prop="powerTemplateId" v-if="userData.brandPartyId==3">
          <el-select size="small" clearable v-model="data.powerTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in cdbTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="烤肠机公司：" prop="hotCompanyId" v-if="userData.brandPartyId==3">
          <el-select size="small" clearable v-model="data.hotCompanyId"
                     placeholder="请选择">
            <el-option v-for="item in kcjList" :key="item.companyId" :label="item.companyName"
                       :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="烤肠机模板：" prop="hotTemplateId" v-if="userData.brandPartyId==3">
          <el-select size="small" clearable v-model="data.hotTemplateId"
                     placeholder="请选择" :disabled="title=='修改订单信息'">
            <el-option v-for="item in kcjTemplate" :key="item.templateId" :label="item.templateName"
                       :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button style="background-color:#e0e0e0;" @click="addOrderDialog=false">取 消</el-button>
    <el-button style="background-color:#e6a23c;color: #eeeeee" @click="keepOrderInfo"
               v-if="title=='录入订单信息'">保 存</el-button>
    <el-button type="primary" @click="addOrderInfo" v-if="title=='录入订单信息'">提 交</el-button>
    <el-button type="primary" @click="editOrderInfo" v-else>修 改</el-button>
        </span>
    </el-dialog>
    <!--    <el-dialog :visible.sync="storeDataDialog" title="选择关联店铺" append-to-body top="25px">-->
    <!--      <div style="margin-bottom: 10px">-->
    <!--        <span>店铺名称：<el-input placeholder="请搜索" size="small" style="width: 180px" v-model="storeName"-->
    <!--                             clearable></el-input></span>-->
    <!--        <el-button size="small" style="background-color:#303e9d;color: #eeeeee;margin-left: 10px-->
    <!--"-->
    <!--                   @click="getNickList">搜索-->
    <!--        </el-button>-->
    <!--      </div>-->
    <!--      <el-table :data="storeData" highlight-current-row-->
    <!--                :cell-style="{ 'textAlign': 'center' }"-->
    <!--                :header-cell-style="{'fontSize': '14px','background-color': '#F3F6FD','color': '#333333','textAlign': 'center' }"-->
    <!--                @selection-change="handleSelectionChange" height="calc(100vh - 280px)">-->
    <!--        <el-table-column-->
    <!--            type="selection"-->
    <!--            width="55">-->
    <!--        </el-table-column>-->
    <!--        <el-table-column prop="storeCode" label="编码"></el-table-column>-->
    <!--        <el-table-column prop="storeName" label="店铺名"></el-table-column>-->
    <!--        <el-table-column prop="address" label="地址" show-overflow-tooltip></el-table-column>-->
    <!--        <el-table-column prop="nickName" label="加盟商"></el-table-column>-->
    <!--        <el-table-column prop="phoneNum" label="加盟商电话"></el-table-column>-->
    <!--      </el-table>-->
    <!--      <span slot="footer">-->
    <!--        <el-button style="color: #eeeeee;background-color:#303e9d;" @click="comfirm">确定</el-button>-->
    <!--    </span>-->
    <!--    </el-dialog>-->
    <init-map ref="initMapD" @addStatus="receiveMessage"></init-map>
  </div>
</template>

<script>
import {mapState} from "vuex";
import initMap from "./initMap.vue";

export default {
  name: "addOrder",
  components: {
    initMap
  },
  data() {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < today.getTime();
        }
      },
      loading: false,
      addOrderDialog: false,
      storeDataDialog: false,
      chargeUserId: "",
      title: "",
      keyword: "",
      address: "",
      projectUserId: "",
      companyMaster: [],
      afterSaleList: [],
      coldList: [],
      furnishList: [],
      cctvList: [],
      storeData: [],
      shelvesList: [],
      addvanceList: [],
      cdbList: [],
      kcjList: [],
      furnishTemplate: [],
      coldTemplate: [],
      shelvesTemplate: [],
      cctvTemplate: [],
      doorTemplate: [],
      addvanceTemplate: [],
      cdbTemplate: [],
      kcjTemplate: [],
      doorList: [],
      storeName: "",
      menageList: [],
      typeList: [{
        id: 1,
        name: "普通店"
      }, {
        id: 2,
        name: "旗舰店"
      }],
      areaList: [],
      designList: [],
      yjsList: [],
      taskList: [],
      data: {
        storeId: "",
        chargeUserId: "",
        designId: "",
        settlementId: "",
        companyId: "",
        templateId: "",
        coldCompanyId: "",
        clodTemplateId: "",
        monitorCompanyId: "",
        monitorTemplateId: "",
        goodsCompanyId: "",
        goodsTemplateId: "",
        adCompanyId: "",
        adTemplateId: "",
        windowsCompanyId: "",
        windowsTemplateId: "",
        afterPhone: "",
        afterName: "",
        afterId: "",
      },
      rules: {}
    }
  },
  created() {
    this.getAreaList()
    // this.getMasterList()
    this.getManegerList()
    this.getAftersaleList()
    // this.getTaskList()
  },
  computed: {
    ...mapState(["userData"]),
  },
  methods: {
    // openStore() {
    //   this.storeDataDialog = true
    //   this.getNickList()
    // },
    getAfterSalesPhone(val) {
      const user = this.afterSaleList.find(item => item.userId === val)
      if (user) {
        this.data.afterPhone = user.phoneNum
        this.data.afterName = user.userName
      }
    },
    getNickList() {
      this.$api.storeGetStoreVo({pageNumber: 1, pageSize: 100000, storeName: this.storeName}).then((res) => {
        this.storeData = res.data
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.chooseStore = val[0]
    },
    // comfirm() {
    //   this.storeDataDialog = false
    //   this.assignName = this.chooseStore.storeName
    //   this.data.storeId = this.chooseStore.storeId
    // },
    changeCompanyId(e) {
      if (this.userData.brandPartyId == 1) {
        this.data.adCompanyId = e
        this.data.windowsCompanyId = e
      }
    },
    openMapDia() {
      this.$refs.initMapD.handleOpen()
    },
    keepOrderInfo() {
      this.$message.success('已保存')
      sessionStorage.setItem('submitFrom', JSON.stringify(this.data))
    },
    receiveMessage(data) {
      this.address = data.address
      this.data.address = data.address
      this.data.lon = data.longitude
      this.data.lat = data.latitude
    },
    addOrderInfo() {
      this.loading = true
      sessionStorage.removeItem('submitFrom')
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          const data = this.data
          this.$api.assignAddAssignTaskNew({
            flag: 1,
            ...data
          }).then(res => {
            if (res == 1) {
              this.$message.success("添加成功！")
              this.addOrderDialog = false
              this.$emit('addStatus', 1);
              this.loading = false
            }
          })
        } else {
          this.$message.warning("请查看必填项！")
          return false;
        }
      });
    },
    handleClose() {
      this.addOrderDialog = false
      this.data = {}
      this.taskList = []
      this.companyMaster = []
    },
    async handleOpen(val) {
      console.log(val, "zhi")
      this.addOrderDialog = true
      this.data = JSON.parse(sessionStorage.getItem('submitFrom')) || {}
      await this.getNickList()
      this.data.storeId = val.storeId
      this.title = "录入订单信息"
      const companyTypes = [1, 2, 3, 4, 5, 6, 7, 8];
      Promise.all(
          companyTypes.map(type =>
              this.$api.companyGetOtherCompanyList({companyType: type, brandPartyId: val.brandPartyId})
          )
      ).then(([data1, data2, data3, data4, data5, data6, data7, data8,]) => {
        this.furnishList = data1;
        this.coldList = data2;
        this.shelvesList = data3;
        this.cctvList = data4;
        this.doorList = data5;
        this.addvanceList = data6;
        this.cdbList = data7;
        this.kcjList = data8;
      }).catch(err => {
        console.error('请求失败：', err);
      });
      const userList = [12, 13];
      Promise.all(
          userList.map(type =>
              this.$api.assignGetUserList({loginType: type})
          )
      ).then(([data1, data2]) => {
        this.yjsList = data1;
        this.designList = data2;
      }).catch(err => {
        console.error('请求失败：', err);
      });
      const supplierType = [1, 2, 3, 4, 5, 6, 7, 8]
      Promise.all(
          supplierType.map(type =>
              this.$api.templateGetTaskTemplateList({
                supplierType: type,
                pageNumber: 1,
                pageSize: 1000,
                brandPartyId: val.brandPartyId
              })
          )
      ).then(([data1, data2, data3, data4, data5, data6, data7, data8]) => {
        this.furnishTemplate = data1.data;
        this.coldTemplate = data2.data;
        this.shelvesTemplate = data3.data;
        this.cctvTemplate = data4.data;
        this.doorTemplate = data5.data;
        this.addvanceTemplate = data6.data;
        this.cdbTemplate = data7.data;
        this.kcjTemplate = data8.data;
        console.log(data1)
      }).catch(err => {
        console.error('请求失败：', err);
      });
    },
    async getAreaList() {
      const res = await this.$api.assignGetAreaList().catch(() => null)
      if (res) {
        this.areaList = res;
      }
    },
    async getMasterList() {
      console.log(this.data)
      const res = await this.$api.companyGetManagerList({companyId: this.data.companyId || null}).catch(() => null)
      if (res) {
        this.companyMaster = res;
      }
      console.log(this.companyMaster)
    },
    async getManegerList() {
      const res = await this.$api.assignGetUserCompany({flag: 1}).catch(() => null)
      if (res) {
        this.menageList = res;
      }
    },
    async getAftersaleList() {
      const res = await this.$api.assignGetUserCompany({flag: 3}).catch(() => null)
      if (res) {
        this.afterSaleList = res;
      }
    },
    async getTaskList() {
      const res = await this.$api.templateGetTaskTemplateList({
        pageSize: 1000,
        pageNumber: 1,
        companyId: this.data.companyId
      }).catch(() => null)
      if (res) {

        this.taskList = res.data;
      }
    },
    async edit(row) {
      await this.getNickList()
      Object.keys(this.data).forEach(key => {
        if (row.hasOwnProperty(key)) {
          this.data[key] = row[key];
        }
      });
      this.data.assignNo = row.assignNo
      this.title = "修改订单信息"
      this.addOrderDialog = true
      const companyTypes = [1, 2, 3, 4, 5, 6];
      await this.getMasterList()
      await this.getTaskList()
      const userList = [12, 13];
      Promise.all(
          userList.map(type =>
              this.$api.assignGetUserList({loginType: type})
          )
      ).then(([data1, data2]) => {
        this.yjsList = data1;
        this.designList = data2;
      }).catch(err => {
        console.error('请求失败：', err);
      });
      Promise.all(
          companyTypes.map(type =>
              this.$api.companyGetOtherCompanyList({companyType: type, brandPartyId: row.brandPartyId})
          )
      ).then(([data1, data2, data3, data4, data5, data6]) => {
        this.furnishList = data1;
        this.coldList = data2;
        this.shelvesList = data3;
        this.cctvList = data4;
        this.doorList = data5;
        this.addvanceList = data6;
      }).catch(err => {
        console.error('请求失败：', err);
      });
      const supplierType = [1, 2, 3, 4, 5, 6]
      Promise.all(
          supplierType.map(type =>
              this.$api.templateGetTaskTemplateList({
                supplierType: type,
                pageNumber: 1,
                pageSize: 1000,
                brandPartyId: row.brandPartyId
              })
          )
      ).then(([data1, data2, data3, data4, data5, data6]) => {
        console.log(111)
        this.furnishTemplate = data1.data;
        this.coldTemplate = data2.data;
        this.shelvesTemplate = data3.data;
        this.cctvTemplate = data4.data;
        this.doorTemplate = data5.data;
        this.addvanceTemplate = data6.data;
        console.log(data1)
      }).catch(err => {
        console.error('请求失败：', err);
      });
    },
    editOrderInfo() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.$api.assignUpdateAssignTask(this.data).then(res => {
            if (res == 1) {
              this.$message.success("修改成功！")
              this.addOrderDialog = false
              this.$emit('addStatus', 1);
            }
          })
        } else {
          this.$message.warning("请查看必填项！")
          return false;
        }
      });

    },

  }
}
</script>

<style scoped>
.el-form-item {
  width: 45%;
}

.el-select {
  width: 100%;
}
</style>